// 数组归并

let salaries = [ 2, 3, 6, 4 ];

let accumulator = function(previousResult, currentElement, currentIndex, arraySelf){
    console.log('previous: ', previousResult );
    console.log('current: ', currentElement , ', index: ', currentIndex );
    return previousResult + currentElement;
}

// 若省略 initial 则以数组第一个元素为初始值
let total = salaries.reduce( accumulator );
console.log( total );

let sum = salaries.reduce( (p,c) => p+c , 0 );
console.log( sum );

console.log( '= '.repeat(30) );

const students = [
    { id: 9527, name: '华安', gender: '男' , score: { math: 78, chinese: 99, english: 59 } },
    { id: 8526, name: '秋香', gender: '女' , score: { math: 89, chinese: 62, english: 61 } },
    { id: 1024, name: '华文', gender: '男' , score: { math: 60, chinese: 48, english: 32 } },
    { id: 2048, name: '华武', gender: '男' , score: { math: 70, chinese: 20, english: 56 } },
    { id: 7777, name: '武状元', gender: '男' , score: { math: 60, chinese: 60, english: 60 } },
    { id: 6666, name: '石榴姐', gender: '女' , score: { math: 60, chinese: 48, english: 56 } }
];

let x = students.reduce( (prev,curr) => prev + curr.score.math , 0 );

console.log( x );

// Array.prototype.reduce( accumulator [, initial] )
// 参数: 
//      第一个参数 accumulator 必须是个函数，它可以有四个参数:
//           previousResult 表示上次调用 accumulator 函数的运算结果
//           currentElement 表示当前需要处理的元素
//           currentIndex 表示当前待处理元素的下标(索引)
//           arraySelf 表示当前正在处理的数组本身
//      第二个参数 initial 是可选的，用于指定 accumulator 的初始值
// 作用: 用 accumulator 将数组诸元素归并成单个值返回
// 返回: 返回归并后的单个值

// 参考文档:
// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce